# coding: utf8
# datetime: 2021-03-18
# 题目地址：https://leetcode-cn.com/problems/reverse-linked-list-ii/


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution(object):
    def reverseBetween(self, head, left, right):
        count = 1
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        while pre.next and count < left:
            pre = pre.next
            count += 1
        cur = pre.next
        tail = cur
        while cur and count <= right:
            nxt = cur.next
            cur.next = pre.next
            pre.next = cur
            tail.next = nxt
            cur = nxt
            count += 1
        return dummy.next


b = ListNode(1)
c = ListNode(2)
d = ListNode(3)
e = ListNode(4)
f = ListNode(5)
b.next = c
c.next = d
d.next = e
e.next = f
a = Solution()
tmp = a.reverseBetween(b, 2, 4)
i = 0
while tmp.next is not None:
    print(tmp.val)
    tmp = tmp.next
    if i == 6:
        break
    i += 1